<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索和操作区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-select v-model="queryParams.waterPlantId" placeholder="请选择水厂" clearable @change="handleSearch"
            style="width: 100%">
            <el-option v-for="item in factoryOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-col>
        <el-col :span="16" class="text-right">
        </el-col>
      </el-row>
    </el-card>
    <el-card class="mt-1">
      <el-button type="primary" @click="showAddDialog">新增配置</el-button>

      <!-- 配置表格 -->
      <el-table :data="configList" border class="mt-2" v-loading="loading" :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
        <el-table-column prop="indicatorName" label="指标名称" />
        <el-table-column label="指标类型">
          <template #default="{ row }">
            {{ getDictLabel(kpiTypeOptions, row.indicatorType) }}
          </template>
        </el-table-column>
        <el-table-column prop="dataSource" label="数据源" />
        <el-table-column prop="dataUnit" label="单位" />
        <el-table-column label="组态类型">
          <template #default="{ row }">
            {{ getDictLabel(configTypeOptions, row.configurationType) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateFrequency" label="更新频率(分钟)" />
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="row.isDisplayed === 1 ? 'success' : 'danger'">
              {{ row.isDisplayed === 1 ? '展示中' : '已隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%" :close-on-click-modal="false">
      <el-form :model="currentConfig" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="水厂" prop="waterPlantId">
          <el-select v-model="currentConfig.waterPlantId" placeholder="请选择水厂" style="width: 100%">
            <el-option v-for="item in factoryOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="+item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="指标类型" prop="indicatorType">
          <el-select v-model="currentConfig.indicatorType" placeholder="请选择指标类型" style="width: 100%">
            <el-option v-for="item in kpiTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="指标名称" prop="indicatorName">
          <el-input v-model="currentConfig.indicatorName" placeholder="请输入指标名称" />
        </el-form-item>
        <el-form-item label="数据源" prop="dataSource">
          <el-input v-model="currentConfig.dataSource" placeholder="请输入数据源" />
        </el-form-item>
        <el-form-item label="单位" prop="dataUnit">
          <el-input v-model="currentConfig.dataUnit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="组态类型" prop="configurationType">
          <el-select v-model="currentConfig.configurationType" placeholder="请选择组态类型" style="width: 100%">
            <el-option v-for="item in configTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="组态详情" prop="configurationDetail">
          <el-input v-model="currentConfig.configurationDetail" type="textarea" :rows="3" placeholder="请输入组态详情" />
        </el-form-item>
        <el-form-item label="展示顺序" prop="displayOrder">
          <el-input-number v-model="currentConfig.displayOrder" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="更新频率(分钟)" prop="updateFrequency">
          <el-input-number v-model="currentConfig.updateFrequency" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否展示" prop="isDisplayed">
          <el-switch v-model="currentConfig.isDisplayed" :active-value="1" :inactive-value="0" active-text="展示"
            inactive-text="隐藏" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getFactoryList,
  getWaterPlantKpiTypeList,
  getConfigurationTypeList,
  getWaterPlantConfigList,
  getWaterPlantConfigDetail,
  addWaterPlantConfig,
  updateWaterPlantConfig,
  deleteWaterPlantConfig
} from '@/api/prod_operate/sys_setting/cockpit/plant_cockpit'

// 加载状态
const loading = ref(false)

// 下拉选项数据
const factoryOptions = ref([])
const kpiTypeOptions = ref([])
const configTypeOptions = ref([])

// 配置列表数据
const configList = ref([])

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  waterPlantId: ''
})

// 当前操作的配置
const currentConfig = reactive({
  configurationId: '',
  waterPlantId: '',
  indicatorType: '',
  indicatorName: '',
  dataSource: '',
  dataUnit: '',
  displayOrder: 1,
  isDisplayed: 1,
  configurationType: '',
  configurationDetail: '',
  updateFrequency: 5
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增配置')
const formRef = ref(null)

// 表单验证规则
const rules = reactive({
  waterPlantId: [
    { required: true, message: '请选择水厂', trigger: 'change' }
  ],
  indicatorType: [
    { required: true, message: '请选择指标类型', trigger: 'change' }
  ],
  indicatorName: [
    { required: true, message: '请输入指标名称', trigger: 'blur' }
  ],
  dataSource: [
    { required: true, message: '请输入数据源', trigger: 'blur' }
  ],
  dataUnit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  configurationType: [
    { required: true, message: '请选择组态类型', trigger: 'change' }
  ],
  displayOrder: [
    { required: true, message: '请输入展示顺序', trigger: 'blur' }
  ],
  updateFrequency: [
    { required: true, message: '请输入更新频率', trigger: 'blur' }
  ]
})

// 根据字典值获取标签
const getDictLabel = (options, value) => {
  const item = options.find(item => item.dictValue === value)
  return item ? item.dictLabel : value
}

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取水厂列表
    const factoryRes = await getFactoryList()
    factoryOptions.value = factoryRes.data

    // 获取指标类型列表
    const kpiTypeRes = await getWaterPlantKpiTypeList()
    kpiTypeOptions.value = kpiTypeRes.data

    // 获取组态类型列表
    const configTypeRes = await getConfigurationTypeList()
    configTypeOptions.value = configTypeRes.data

    // 获取配置列表
    await fetchConfigList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取配置列表
const fetchConfigList = async () => {
  try {
    loading.value = true
    const res = await getWaterPlantConfigList(queryParams)
    configList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchConfigList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchConfigList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchConfigList()
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增配置'
  resetCurrentConfig()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await getWaterPlantConfigDetail(row.configurationId)
    Object.assign(currentConfig, res.data)
    dialogTitle.value = '编辑配置'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取配置详情失败:', error)
    ElMessage.error('获取配置详情失败')
  } finally {
    loading.value = false
  }
}

// 重置当前配置
const resetCurrentConfig = () => {
  currentConfig.configurationId = ''
  currentConfig.waterPlantId = queryParams.waterPlantId || ''
  currentConfig.indicatorType = ''
  currentConfig.indicatorName = ''
  currentConfig.dataSource = ''
  currentConfig.dataUnit = ''
  currentConfig.displayOrder = 1
  currentConfig.isDisplayed = 1
  currentConfig.configurationType = ''
  currentConfig.configurationDetail = ''
  currentConfig.updateFrequency = 5
}

// 确认保存
const confirmSave = async () => {
  try {
    await formRef.value.validate()

    if (dialogTitle.value === '新增配置') {
      await addWaterPlantConfig(currentConfig)
      ElMessage.success('新增配置成功')
    } else {
      await updateWaterPlantConfig(currentConfig)
      ElMessage.success('修改配置成功')
    }

    dialogVisible.value = false
    fetchConfigList()
  } catch (error) {
    console.error('保存配置失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除配置 "${row.indicatorName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteWaterPlantConfig(row.configurationId)
      ElMessage.success('删除成功')
      fetchConfigList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.text-right {
  text-align: right;
}

.mt-2 {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 表格内容居中对齐 */
:deep(.el-table th),
:deep(.el-table td) {
  text-align: center !important;
}

/* 表格单元格内边距 */
:deep(.el-table .cell) {
  padding: 8px;
}
</style>